package cn.vastbase.jdbc.batch;

import org.junit.Test;

import java.sql.*;

public class OpenGaussBatchTestCase {

    /* 定义连接对象 */
    static Connection conn = null;
    static String cname = "org.opengauss.Driver";
    static String url = "jdbc:opengauss://172.16.55.138:15400/zxsdb_a?reWriteBatchedInserts=true&batchMode=off";
    static String username = "zxs";
    static String passwd = "Vastdata#0730";
    /* 定义 SQL 语句执行对象 */
    static Statement stmt = null;
    static PreparedStatement pstmt = null;
    /* 定义结果集对象 */
    static ResultSet rs = null;

    public Connection conn() {
        try {
            Class.forName(cname);
            return conn = DriverManager.getConnection(url, username, passwd);
        } catch (ClassNotFoundException | SQLException e) {
            System.out.println("[FAIL] conn database fail." + e.getMessage());
        }
        return null;

    }

    public void close() {
        try {
            /* 关闭结果集对象 */
            if (rs != null)
                rs.close();
        } catch (SQLException e) {
            System.out.println("[FAIL] close resultSet fail." + e.getMessage());
        }
        try {
            /* 关闭语句对象 */
            if (stmt != null)
                stmt.close();
        } catch (SQLException e) {
            System.out.println("[FAIL] close statement fail." + e.getMessage());
        }
        try {
            /* 关闭语句对象 */
            if (pstmt != null)
                pstmt.close();
        } catch (SQLException e) {
            System.out.println("[FAIL] close statement fail." + e.getMessage());
        }
        try {
            /* 关闭连接 */
            conn.close();
        } catch (SQLException e) {
            System.out.println("[FAIL] close connection fail." + e.getMessage());
        }
    }

    /**
     * batchMode批量插入数据
     *
     * @throws SQLException
     */
    @Test
    public void testBatchs() throws SQLException {

        if (conn() == null)
            return;

//        Properties props = new Properties();
//        props.put("batchMode", "OFF");
//        props.setProperty("reWriteBatchedInserts", "true");
//        conn.setClientInfo(props);
        try {
            pstmt = conn.prepareStatement("insert into t2 (id) values(?)");
            for (int i = 0; i < 5; i++) {
                pstmt.setInt(1, i);
                pstmt.addBatch();
            }
            pstmt.executeBatch();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            conn.close();
        }
    }
}
